const express = require("express");
const router = express.Router();
const { success, failure } = require("../utils/response");
const { User } = require("../models");
const { NotFound, BadRequest, Unauthorized } = require("http-errors");
const bcrypt = require("bcryptjs");
const { Op } = require("sequelize");
const jwt = require("jsonwebtoken");
const validate = require("../middlewares/validate-captcha");
const { delKey } = require("../utils/redis");
const sendMail = require("../utils/mail");

// 用户注册接口
router.post("/sign_up", validate, async (req, res) => {
  try {
    const { email, username, password, nickname, sex, role } = req.body;
    const body = {
      email,
      username,
      password,
      nickname,
      sex,
      role,
    };
    const user = await User.create(body);
    delete user.dataValues.password;
    // 请求成功，删除验证码，防止重复使用
    await delKey(req.body.captchaKey);
    // 发送邮件
    const html = `
  您好，<span style="color: red">${user.nickname}。</span><br><br>
  恭喜，您已成功注册会员！<br><br>
  请访问<a href="https://clwy.cn">「长乐未央」</a>官网，了解更多。<br><br>
  ━━━━━━━━━━━━━━━━<br>
  长乐未央
`;
    await sendMail(user.email,`[长乐未央]的注册成功通知`,html)
    success(res, "注册成功", { user }, 201);
  } catch (error) {
    failure(res, error);
  }
});

router.post("/sign_in", async (req, res) => {
  try {
    // 参数验证
    const { login, password } = req.body;

    if (!login) {
      throw new BadRequest("邮箱或用户名必须填写！");
    }
    if (!password) {
      throw new BadRequest("用户密码必须填写！");
    }
    // 编写查询条件
    const condition = {
      where: {
        [Op.or]: [{ email: login }, { username: login }],
      },
    };
    // 查询用户并验证用户是否存在
    const user = await User.findOne(condition);
    if (!user) {
      throw new NotFound("用户不存在");
    }
    // 验证密码
    let flag = bcrypt.compareSync(password, user.password);
    if (!flag) {
      throw new Unauthorized("密码错误！");
    }
    // 生成身份令牌 要加密的参数，盐值，过期时间
    const token = jwt.sign(
      {
        userId: user.id,
      },
      process.env.SECRET,
      { expiresIn: "30d" }
    );
    success(res, "登录成功", { token });
  } catch (error) {
    failure(res, error);
  }
});
module.exports = router;
